// pages/buy/buy.js
import { getWechatProOpenIdIdByCode, bpPay } from '../../api/index'
import { showLoading, showToast, hideLoading } from '../../utils/toast'

const globalData = getApp().globalData
Page({

  /**
   * 页面的初始数据
   */
  data: {
    packageObj: globalData.packageObj
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      packageObj: globalData.packageObj
    })
    setTimeout(() => {
      this.payData()
    }, 400);
  },
  goBack() {
    let path = 'pages/index/index?backurl=' + encodeURIComponent('https://siq.biaopu.cloud/home')
    // let path = 'pages/index/index?backurl=' + encodeURIComponent('https://siq-pre.biaopu.cloud/home')
    wx.navigateToMiniProgram({
      // appId: 'wxaccb0965e22e2d19',  // 测试版appId
      appId: 'wx7eb47e7f00f69ac0',  // 生产版appId
      path,
      // envVersion: 'trial',  // 体验版
      envVersion: 'release',  // 正式版
      success(res) {
        // 打开成功
      }
    })
  },
  launchAppError(e) {
    console.log('launchAppError')
    console.log(e.detail.errMsg)
  },
  // 支付
  payData() {
    let packageCode = globalData.packageObj.packageCode
    if (!packageCode) {
      showToast('无对应套餐')
      return
    }
    let that = this
    wx.login({
      success: async (res) => {
        let code = res.code
        try {
          showLoading('获取数据中')
          let result = await getWechatProOpenIdIdByCode({ code, token: globalData.token })
          let payResult = await bpPay({
            channelNo: 'wechat-pro',
            openId: result.openid,
            packageCode,
            token: globalData.token
          })
          hideLoading()
          wx.requestPayment({
            timeStamp: payResult.timeStamp.toString(),
            nonceStr: payResult.nonceStr,
            package: payResult.packageStr,
            signType: payResult.signType,
            paySign: payResult.paySign,
            success(res) {
              showToast('支付成功')
              if (globalData.packageObj.siqSource !== 'app') {
                that.goBack()
              }
            },
            fail(res) {
              console.info(res)
              console.info('支付失败')
            }
          })
        } catch (error) {
          console.info('error')
          console.info(error)
          setTimeout(() => {
            hideLoading()
          }, 2000)
        }
      },
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
})